package com.alibaba.citrus.cr.mn.order.center.facade.function.impl;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.*;
import com.alibaba.citrus.cr.mn.order.center.common.SetOrderTag;
import com.alibaba.citrus.cr.mn.order.center.common.util.StopWatchUtils;
import com.alibaba.citrus.cr.mn.order.center.facade.function.asynctask.OrderAsyncTaskListenerConsumerSelector;
import com.alibaba.citrus.cr.mn.order.center.facade.function.check.ExchangeOrderSubmitParamsBizCheck;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.AbstractOrderBizSubmitService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.OrderAtomSubmitService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.mnordercenter.model.dto.OrderAtomSubmitResponse;
import com.epoch.app.mnordercenter.orderbaserequest.OrderAtomBatchSubmitRequest;
import com.epoch.app.mnordercenter.orderbaserequest.OrderAtomSubmitRequest;
import com.epoch.app.mnordercenter.orderbaserequest.OrderBizBatchSubmitRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName SalesOrderBizCreateServiceImpl
 * @description: TODO
 * @date 2023/05/16 14:04
 * @version: 1.0
 */
@Service("exchangeOrderBizSubmitService")
public class ExchangeOrderBizSubmitServiceImpl extends AbstractOrderBizSubmitService {
    private static final Log log = Log.getLogger(ExchangeOrderBizSubmitServiceImpl.class);
    @Resource(name = "exchangeOrderAtomSubmitService")
    private OrderAtomSubmitService exchangeOrderAtomSubmitService;

    @Resource(name = "orderAsyncTaskExchangeOrderCreateComponent")
    private OrderAsyncTaskListenerConsumerSelector orderAsyncTaskExchangeOrderCreateComponent;

    @Resource
    private ExchangeOrderSubmitParamsBizCheck exchangeOrderSubmitParamsBizCheck;

    @Override
    public void paramsInvalidCheck(OrderBizBatchSubmitRequest bizBatchSubmitRequest) {
        StopWatchUtils.start("订单中心商业提交", "paramsInvalidCheck");
        List<OrderAtomSubmitRequest> orderList = Optional.ofNullable(bizBatchSubmitRequest.getOrderList())
                .orElse(Lists.newArrayList());
        exchangeOrderSubmitParamsBizCheck.paramsInvalidCheck(orderList, Lists.newArrayList());
        StopWatchUtils.stop();
    }

    @Override
    public String getOrderTag() {
        return SetOrderTag.EXCHANGE;
    }

    @Override
    public void processAtomAbility(OrderAtomBatchSubmitRequest request, List<OrderAtomSubmitResponse> responses) {
        if (CollectionUtils.isEmpty(request.getOrderList())) {
            return;
        }

        Result<List<OrderAtomSubmitResponse>> atomSubmitResult = atomBatchSubmit(request);
        log.info("商业调用原子批量提交销售订单 Result={}", JSONObject.toJSONString(atomSubmitResult));

        if (CollectionUtils.isEmpty(atomSubmitResult.getResult())) {
            List<String> salesOrderNos = request.getOrderList().stream()
                    .map(OrderAtomSubmitRequest::getSalesOrderNo).distinct().collect(Collectors.toList());
            orderAsyncTaskExchangeOrderCreateComponent.sendOccupyInventoryOccupyMsg(salesOrderNos);
        } else {
            // TODO 此处需要筛选出来成功的数据
            List<String> salesOrderNos = atomSubmitResult.getResult().stream()
                    .map(OrderAtomSubmitResponse::getSalesOrderNo).distinct().collect(Collectors.toList());
            orderAsyncTaskExchangeOrderCreateComponent.sendOccupyInventoryOccupyMsg(salesOrderNos);
        }

        if (CollectionUtils.isNotEmpty(atomSubmitResult.getResult())) {
            responses.addAll(atomSubmitResult.getResult());
        }
    }

    @FacadeInvoker(value = "批量提交换货订单", errorCode = "OC-03-001-01-16-006")
    public Result<List<OrderAtomSubmitResponse>> atomBatchSubmit(OrderAtomBatchSubmitRequest atomSubmitRequest) {
        try {
            log.error("ExchangeOrderBizSubmitServiceImpl#atomBatchSubmit request={}", JSONObject.toJSONString(atomSubmitRequest));
            List<OrderAtomSubmitResponse> submitResponses = exchangeOrderAtomSubmitService.batchSubmit(atomSubmitRequest.getOrderList());
            return Result.success(submitResponses, "", "");
        } catch (FunctionException | FacadeException | ProcessException | ActivityException | RepositoryException e) {
            log.error("商业调用原子批量提交换货订单失败", e);
            return Result.fail(e.getErrorCode(), e.getErrorMessage());
        } catch (Throwable throwable) {
            log.error("商业调用原子批量提交换货订单失败", throwable);
            if (throwable instanceof RuntimeException) {
                FacadeSystemException e = new FacadeSystemException(throwable);
                return Result.fail(e.getErrorCode(), e.getErrorMessage());
            }
            SystemException exception = new SystemException("OC-00-000-01-99-001");
            return Result.fail(exception.getErrorCode(), exception.getErrorMessage());
        }
    }
}
